<?php

/**
 * 登录
 */

namespace app\home\controller;

use think\Db;
use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class Login extends Controller {

    public function index() {
        return view('regin');
    }

    public function login(){
        return view('login');
    }

    public function regin(){

        $request = Request::instance();
        $post = $request->post();

        $post['agent_password'] = md5($post['agent_password']);

        $infos = Db::name('education_business_login')->where('username',$post['agent_tel'])->find();

        if(!empty($infos))
        {
            echo json_encode(['code'=>'1003','msg'=>'此用户已注册']);exit();
        }


        $arr = [
            'username'=>$post['agent_tel'],
            'pwd'=>$post['agent_password']
        ];

        Db::name('education_business_login')->insert($arr);
        $id = Db::getLastInsID();

        Db::name('education_business_login')->where('id',$id)->update(['p_id'=>$id]);

        $arr2 = [
            'b_id'=>$id,
            'user_name'=>$post['agent_tel'],
            'p_id'=>$id,
        ];

        $res = Db::name('education_business')->insert($arr2);

        if (!empty($res)) {
            echo json_encode(['code'=>'1000','msg'=>'注册成功']);
            // $this->redirect('base/index');
        } else {
            return json_encode(['code'=>'1001','msg'=>'注册失败']);
            // $this->error('登录失败', 'login/index');
        }

    }

    public function doLogin() {
        $request = Request::instance();
        $post = $request->post();

        $agent_password = md5($post['agent_password']);
        $res = Db::table('h_education_business_login')->where("username = '{$post['agent_username']}' AND pwd = '$agent_password'")->find();

        if (!empty($res)) {

            $info = Db::name('education_business_login')->where("username = '{$post['agent_username']}'")->find();

            if($info['status'] == 0){
                echo json_encode(['code'=>'1002','msg'=>'未审核']);
            }else if($info['status'] == 2){
                echo json_encode(['code'=>'1001','msg'=>'审核未通过']);
            }elseif($info['status'] == 1){
                Session::set('agent_info',$res);
                echo json_encode(['code'=>'1000','msg'=>'登录成功']);
            }

            // $this->redirect('base/index');
        } else {
            return json_encode(['code'=>'1001','msg'=>'登录失败']);
            // $this->error('登录失败', 'login/index');
        }
    }
    public function loginOut(){
        $agent_info = Session::get('agent_info');
        if(!empty($agent_info)){
            Session::clear();
            $this->redirect('Login/index');
        }
    }

}
